#!/usr/bin/php

<?php

@error_reporting(E_ALL ^ E_NOTICE);
@set_time_limit(0);
require('./includes/dbconfig.php');
require('./includes/api/class.api.php');
require('./includes/api/class.assetlist.php');

//Connect to DB
$link = mysql_connect($dbserver, $dbuser, $dbpass)
or die('Could not connect: ' . mysql_error());
mysql_select_db($dbase) or die('Could not select database');

//Delete current assets from DB
$sql = 'DELETE QUICK FROM `assets`;';
mysql_query($sql);

// Retrieve API keys and fetch extra details from API
$sql    = 'SELECT * FROM `apikeys` WHERE `director` = 1';
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$api = new Api();

// Set API full logon details for corp info access
$api->setCredentials($row['userID'], $row['apiKey'], $row['charID']);
$corp = true;
$apiassetsxml = $api->getAssetList($corp,30);
$apiassets    = array();
$apiassets    = AssetList::getAssetList($apiassetsxml);
getNames($apiassets, null, $corp, $row);

$sql    = 'SELECT * FROM `apikeys`';
$result = mysql_query($sql);
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
  $corp = false;

  // Set API full logon details for persoanl info access
  $api->setCredentials($row['userID'], $row['apiKey'], $row['charID']);

  // Get XML and process using API class
  $apiassetsxml = $api->getAssetList($corp,30);
  $apiassets    = array();
  $apiassets    = AssetList::getAssetList($apiassetsxml);
  $apiassets    = getNames($apiassets, null, $corp, $row);
}

function getNames($assets, $containerID, $corp, $row) {
  if(is_array($assets)) {
      foreach($assets as &$thisasset) {
        $contents = array();
        if(isset($thisasset['contents'])) {
          getNames($thisasset['contents'], $thisasset['itemID'], $corp, $row);
        }
        $itemsql               = 'SELECT * FROM `invtypes` WHERE `typeID` = '.$thisasset['typeID'];
        $itemresult            = mysql_query($itemsql);
        $itemrow               = mysql_fetch_array($itemresult,MYSQL_ASSOC);
        if(!isset($thisasset['locationID'])) {
          $thisasset['locationID'] = 'NULL';
        }
        if(!isset($containerID)) {
          $containerID = 'NULL';
        }
        if($corp){
          $ownerID = 0;
        } else {
          $ownerID = $row['charID'];
        }
        $sql = "INSERT IGNORE INTO `assets` VALUES(".$thisasset['itemID'].",".$ownerID.",".$containerID.",".$thisasset['locationID'].",".
        $thisasset['typeID'].",'".$itemrow['typeName']."',".$thisasset['quantity'].",".$thisasset['flag'].",".$thisasset['singleton'].");";
        $result = mysql_query($sql);
      }
    } else {
      echo 'Need Full API key for '.$row['username'].'\'s character with charID: '.$row['charID'].'<br />';
    }
  }
  ?>